<?php
namespace models\service;
use entities;

class CurrentUser {

	public static $user;
	
	public static $errorMessage;

	private function __construct() {
	}

	public static function user() {
		
		if(!isset(self::$user)) {

			$CI =& get_instance();	
			
			if (!$user_id = $CI->session->userdata('user_id')) {
				return FALSE;
			}

			$criteria = array('userId' => $user_id);
			$u = $CI->em->getRepository('\models\entities\User')->findOneBy($criteria);
			if (!$u) {				
				return FALSE;
			}

			self::$user = $u;
		}

		return self::$user;
	}
	
	public static function getErrorMessage(){
		return self::$errorMessage;
	}

	public static function login($username, $password) {
		$CI =& get_instance();	
		$criteria = array('userId' => $username);
		$u = $CI->em->getRepository('\models\entities\User')->findOneBy($criteria);
		echo "<pre>";print_r($u);
		
		// get User object by username
		if ($u != NULL) {
			
			// this mutates (encrypts) the input password
			$u_input = new \models\entities\User;
			$u_input->setPassword($password);
			
			// password match (comparing encrypted passwords)
			if ($u->getPassword() == $u_input->getPassword()) {
				unset($u_input);
				
				if ($u->getStatus() == 1){
					//die('ssss');		
					$CI->session->set_userdata('user_id',$u->getUserId());
					
					self::$user = $u;
					
					return TRUE;
				} else {
					self::$errorMessage = "User tidak aktif";
					return FALSE;
				}
				 
			}
			self::$errorMessage = "Password yang dimasukkan salah";
			unset($u_input);
		} else {
			self::$errorMessage = "User tidak ditemukan";	
		}		
		// login failed
		return FALSE;

	}

	public function __clone() {
		trigger_error('Clone is not allowed.', E_USER_ERROR);
	}

}